package com.yupi.yuojbackendcommon.interceptor;

import cn.hutool.core.text.AntPathMatcher;
import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWTUtil;
import com.yupi.yuojbackendcommon.common.ErrorCode;
import com.yupi.yuojbackendcommon.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器
 */
@Component
@Slf4j
public class LoginCheckInterceptor implements HandlerInterceptor {

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 放行 OPTIONS 请求
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            return true;
        }

        // 获取请求路径
        String path = request.getRequestURI();

        // 放行内部调用请求 (路径中包含 'inner')
        if (antPathMatcher.match("/**/inner/**", path)) {
            return true;
        }

        // 放行包含 'login' 的路径 (模糊匹配)
        if (antPathMatcher.match("/**/login/**", path)) {
            return true;
        }
        // 放行包含 'login' 的路径 (模糊匹配)
        if (antPathMatcher.match("/**/register/**", path)) {
            return true;
        }

        // 获取 token
        String token = request.getHeader("token");
        log.info("令牌={}", token);

        // 如果 token 为空，不放行
        if (StrUtil.isEmpty(token)) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR, "token为空");
        }

        // token 存在，解析 token，如果解析失败，就返回未登录
        try {
            JWTUtil.parseToken(token);
        } catch (Exception exception) {
            log.error("token 解析失败", exception);
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }

        return true;
    }
}